/**
 * 修复数据
 */
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const dataBaseDir = 'E:/code/electron/dream/src/data/'

const db = low(new FileSync(`${dataBaseDir}/movie.json`))

const movies = db.read()
    .get('movies')
    .value()
setMovieVideoInfo()
db.read()
    .set('movies', movies)
    .write()

function setMovieVideoInfo() {
    for (let movie of movies) {
        if (movie.duration !== 0) {
            continue
        }
        let duration = 0
        let size = 0
        for (let dreamVideo of movie.dreamVideos) {
            duration += dreamVideo.duration
            size += dreamVideo.size
        }
        movie.duration = Math.round(duration)
        movie.durationF = formatSeconds(duration)
        movie.size = size
        movie.sizeF = formatBytes(size)
        console.log(movie)
    }
}

function updateDurationF() {
    for (let movie of movies) {
        for (let dreamVideo of movie.dreamVideos) {
            if (dreamVideo.duration) {
                dreamVideo.durationF = dreamVideo.durationF.replace('00:', '')
                dreamVideo.sizeF = formatBytes(dreamVideo.size, 0)
                console.log(dreamVideo)
            }
        }
    }
}

function formatSeconds(seconds) {
    // 四舍五入取整
    seconds = Math.round(seconds)
    // 计算小时、分钟和秒
    const hrs = Math.floor(seconds / 3600)
    const mins = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60

    let result = ''
    // 将小时、分钟和秒格式化为字符串
    if (hrs > 0) {
        result = hrs.toString().padStart(2, '0') + ':'
    }if (mins > 0) {
        result += mins.toString().padStart(2, '0') + ':'
    }
    result += secs.toString().padStart(2, '0')
    // 组合成最终的时间字符串
    return result
}

function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0'

    const k = 1024
    const sizes = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']

    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return (
        parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + sizes[i]
    )
}
